package com.hznu.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hznu.commonutils.handler.CustomException;
import com.hznu.commonutils.handler.GlobalExceptionHandler;
import com.hznu.ucenter.entity.Center;
import com.hznu.ucenter.entity.Decrypt;
import com.hznu.ucenter.entity.Msg;
import com.hznu.ucenter.entity.Vehicle;
import com.hznu.ucenter.entity.vo.SendMsgVo;
import com.hznu.ucenter.func.cpabe.object.InterValue;
import com.hznu.ucenter.func.main.Cpabe;
import com.hznu.ucenter.mapper.CenterMapper;
import com.hznu.ucenter.service.CenterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hznu.ucenter.service.MsgService;
import com.hznu.ucenter.service.VehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cdd
 * @since 2021-03-19
 */
@Service
public class CenterServiceImpl extends ServiceImpl<CenterMapper, Center> implements CenterService {

    @Autowired
    @Qualifier("redisTemplate1")
    private RedisTemplate redisTemplate;

    @Autowired
    private VehicleService vehicleService;

    @Autowired
    private MsgService msgService;

    @Override
    public void insertCenter(Center center) {
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        center.setCenterTime(localDateTime);
        baseMapper.insert(center);
    }

    @Override
    public void removeCenter(Long centerId) {
        QueryWrapper<Center> wrapper = new QueryWrapper<>();
        wrapper.eq("center_id",centerId);
        int delete = baseMapper.delete(wrapper);
        if(delete == 0) {
            throw new CustomException(20001,"删除失败");
        }
    }

    @Override
    public void updateCenter(Center center) {
        QueryWrapper<Center> wrapper = new QueryWrapper<>();
        wrapper.eq("center_id",center.getCenterId());
        baseMapper.update(center,wrapper);
    }

    @Override
    public void encodeAndSend(SendMsgVo sendMsgVo) {
        // 根据centerId 查数据
        QueryWrapper<Center> wrapper = new QueryWrapper<>();
        wrapper.eq("center_id",sendMsgVo.getCenterId());
        Center center = baseMapper.selectOne(wrapper);

        Msg msg = new Msg();
        msg.setMsgId(3);
        msg.setRsuId(sendMsgVo.getRsuId());
        msg.setMsgDetail(center.getCenterDetail());
        msg.setMsgType(center.getCenterType());
        msg.setMsgTime(center.getCenterTime().toString());

        String plaintext,policy;
        policy = sendMsgVo.getMsgStrategy();
        InterValue interValue;
        Cpabe cpabe = new Cpabe();
        plaintext = "信息内容："+center.getCenterDetail()+",信息类型："+center.getCenterType()+",发送时间："+center.getCenterTime();
        //信息加密
        interValue = cpabe.Myencryot(plaintext,policy);
        //发送
        msg.setEncrypted(interValue.getEncrypted());
        redisTemplate.opsForHash().put("RsuMsgs",msg.getMsgId(),msg);
//        redisTemplate.expire("RsuMsgs",60, TimeUnit.MINUTES);
    }

    @Override
    public void getPriKey(Vehicle vehicle) {
        Cpabe cpabe = new Cpabe();
        //密钥生成
        InterValue value = cpabe.Mykeygen(vehicle.toString());
        //秘钥打包
        vehicle.setVehicleKey(value.getAttKey()+","+value.getPriKey());

        QueryWrapper<Vehicle> wrapper = new QueryWrapper<>();
        wrapper.eq("vehicle_id",vehicle.getVehicleId());
        vehicleService.update(vehicle,wrapper);
        System.out.println(vehicle.getVehicleKey());
    }

    @Override
    // decrypt.getAttkey(),decrypt.getPrikey(),decrypt.getRsuid())
    public List<String> decode(Decrypt decrypt) {
        // 根据RSUId获取信息
        QueryWrapper<Msg> wrapper = new QueryWrapper<>();
        wrapper.eq("rsu_id",decrypt.getRsuid());
        List<Msg> list = msgService.list(wrapper);
        // 返回结果
        List<String> request = new ArrayList<>();
        // 解密
        Cpabe cpabe = new Cpabe();
        InterValue value = new InterValue();
        for (Msg l:list) {
            System.out.println("decrypt.getAttkey():=============" + decrypt.getAttkey());
            System.out.println("decrypt.getPrikey()==============" + decrypt.getPrikey());
            System.out.println("l.getEncrypted()===============" + l.getEncrypted());

            value=cpabe.Mydecrypt(decrypt.getAttkey(),decrypt.getPrikey(),l.getEncrypted());
            if (value.getPlaintext()!="null"){
                request.add(value.getPlaintext());
            }
            System.out.println(value.getPlaintext());
        }
        return request;
    }
}
